/**
 * 富文本组件 配合form组件使用
 * @Author: linzy
 * @Date: 2022-10-09
 * @function Editor
 * @param {array} controls - 控制组件数组
 * @param {object} fontFamilies - 字体数组
 * @param {*} ... - BraftEditor组件 属性
 * @example
 *  <Editor />
 */
import React, { useRef } from "react";
import { useConstants } from "@/hooks";
import { message } from "antd";
import ossUpload from "@/utils/ossUpload";
import BraftEditor from "braft-editor";
import "braft-editor/dist/index.css";
import { setDefaultAttrs } from "@/hooks/tools";
import "./index.css";
const controls = [
  "undo",
  "redo",
  "separator",
  "font-family",
  "font-size",
  "headings",
  "separator",
  "bold",
  "italic",
  "underline",
  "separator",
  "text-indent",
  "text-align",
  "separator",
  "list-ul",
  "list-ol",
  "separator",
  "link",
  "media",
  "separator",
  "remove-styles",
  "clear",
];
const fontFamilies = [
  {
    name: "宋体",
    family: "宋体,SimSun",
  },
  {
    name: "微软雅黑",
    family: "微软雅黑,Microsoft YaHei",
  },
  {
    name: "Araial",
    family: "Arial, Helvetica, sans-serif",
  },
  {
    name: "Georgia",
    family: "Georgia, serif",
  },
  {
    name: "Impact",
    family: "Impact, serif",
  },
  {
    name: "Monospace",
    family: '"Courier New", Courier, monospace',
  },
  {
    name: "Tahoma",
    family: 'tahoma, arial, "Hiragino Sans GB", 宋体, sans-serif',
  },
  {
    name: "楷体",
    family: "楷体,楷体_GB2312, SimKai",
  },
  {
    name: "黑体",
    family: "黑体, SimHei",
  },
];

export default (props = {}) => {
  const { FILE_SERVER } = useConstants();
  const editorInstance = useRef();
  setDefaultAttrs(props, {
    controls,
    fontFamilies,
  });
  /**
   * @description 媒体库上传回调
   * @param {param} 上传的文件
   */
  const uploadFn = (param) => {
    let mediaList = editorInstance.current.getFinderInstance().getItems();
    let videoInMediaList = mediaList.filter((t) => t.type === "VIDEO");

    if (param.file.type.includes("image")) {
      editorUploadImage(param);
    } else if (param.file.type.includes("video")) {
      if (videoInMediaList && videoInMediaList.length > 1) {
        message.error("只能上传一个视频！");
        param.error();
        return false;
      } else {
        editorUploadVideo(param);
      }
    }
  };

  const _dataURItoBlob = (dataURI) => {
    let byteString;
    if (dataURI.split(",")[0].indexOf("base64") >= 0)
      byteString = atob(dataURI.split(",")[1]);
    else byteString = unescape(dataURI.split(",")[1]);
    let mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
    let ia = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {
      type: mimeString,
    });
  };

  /**
   * @description 上传图片的方法
   */
  const editorUploadImage = param => {
    const { file, progress, error, success, libraryId } = param
    ossUpload({
      file,
      type: 'image', onProgress: progress, onError: error,
      onSuccess: (data) => {
        success({
          url: `${FILE_SERVER}${data.id || data["TFS_FILE_NAME"]
            }`,
          meta: {
            id: libraryId
          }
        })
      }
    })
  };
  /**
   * @description 上传视频的方法
   * @param {param} 文件信息
   */
  const editorUploadVideo = (param) => {
    const videoInfo = props.videoInfo;
    const file = param.file;
    ossUpload({
      videoInfo,
      isNormal: true,
      file: file,
      onSuccess: ({ viewUrl, cover }) => {
        let videoData = {
          url: viewUrl,
          meta: {
            id: param.libraryId,
            poster: `${FILE_SERVER}${cover}`,
          },
        };
        param.success({ ...videoData });
      },
      onProgress: ({ percent }) => {
        param.progress(percent);
      },
      onError: ({ err }) => {
        message.error(`上传失败:${err}，请重试！`);
        param.error();
      },
      beforeUpload: () => {
        const fileSize = Number((file.size / (1024 * 1024)).toFixed(1));
        if (fileSize > 500) {
          message.error(`文件不能超过${500}M，请压缩后重新上传！`);
          return false;
        }
        return true;
      },
    });
  };
  return (
    <div className="editor_container">
      <BraftEditor
        {...props}
        ref={editorInstance}
        media={{
          uploadFn: (params) => uploadFn(params),
        }}
      />
    </div>
  );
};
